package com.gogowan.agroenterprise.newview;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.ChanPinRequest;
import com.gogowan.agroenterprise.model.DealerListResult;
import com.gogowan.agroenterprise.model.DealerRequest;
import com.gogowan.agroenterprise.model.GetStoreRuest;
import com.gogowan.agroenterprise.model.OrderEditHeadRequest;
import com.gogowan.agroenterprise.model.OrderEditRequest;
import com.gogowan.agroenterprise.model.ReplaceCodeRequest;
import com.gogowan.agroenterprise.model.StoreModel;
import com.gogowan.agroenterprise.model.UserType;
import com.gogowan.agroenterprise.utils.DialogUitl;
import com.gogowan.agroenterprise.utils.INewAdapterClick;
import com.gogowan.agroenterprise.utils.ListDataSave;
import com.gogowan.agroenterprise.utils.NetWorkManger;
import com.gogowan.agroenterprise.utils.ToastUtils;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.adapter.HwScanAdapter;
import com.gogowan.agroenterprise.widget.xlistview.BottomTongYongDialog;
import com.gogowan.agroenterprise.widget.xlistview.DialogCloseLinstner;
import com.gogowan.agroenterprise.widget.xlistview.DialogTextCHangedLinstner;
import com.gogowan.agroenterprise.widget.xlistview.WorkStateBean;
import com.google.gson.reflect.TypeToken;
import com.ioid.utils.JsonUtils;
import com.ioid.utils.StringUtils;
//import com.lixz.zxing.DefScanActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

//退货
public class NewEditOrderActivity extends BaseActivity {
    private ProgressDialog progressDialog;
    private EditText editText;
    //    private Spinner spinner;
    private TextView scancount_tv;
    // 扫码返回的list
    private ArrayList<String> resultStringList=new ArrayList<>();
    // 总的list
    private List<String> codeStringList = new ArrayList<String>();
    private List<WorkStateBean> dealerList = new ArrayList<WorkStateBean>();
    private ArrayList<String> dealerListName = new ArrayList<String>();
    //    private ArrayList<String> ChanPinListName = new ArrayList<String>();
    private ArrayList<String> storeListName = new ArrayList<String>();
    private ArrayList<StoreModel>  storeList= new ArrayList<>();
//    private ArrayList<StoreModel>  hwList= new ArrayList<>();
//    private ArrayList<StoreModel>  hwList2= new ArrayList<>();

    private HwScanAdapter stringAdapater;
    private ListView listView;
    private ArrayAdapter<String> jxsAdapter;


    private ArrayAdapter<String> ckAdapter,ckAdapter2;
    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 10://经销商
                    jxsAdapter.notifyDataSetChanged();
                    break;
                case 6://经销商
                    ckAdapter2.notifyDataSetChanged();
                    break;
                case 0://经销商
//                    adapter.notifyDataSetChanged();
                    if(dialogTHJXS!=null)
                        dialogTHJXS.setDialogAdapterChanged(dealerList);
                    break;
                case 5://产品
//                    cpAdapter.notifyDataSetChanged();
                    if(dialogCPName!=null)
                        dialogCPName.setDialogAdapterChanged(chanPinList);
                    break;
                case 1://仓库
                    ckAdapter.notifyDataSetChanged();
                    break;
                case 2:
//				xMListViewAdapter.notifyDataSetChanged();
//				SC_Tv.setText(boxCodeList.size()+"个码");
                    scancount_tv.setText(codeStringList.size()+"");
                    break;
                default:
                    break;
            }
        }
    };
    private Spinner ckSpinner,ckSpinner2;
    private int usertype;
    //    private String dealerID;
//    private Spinner sp_cp_name;
//    private ArrayAdapter<String> cpAdapter;
    private List<WorkStateBean> chanPinList=new ArrayList<>();
    private EditText et_di,et_guige;
    private int dealerPositon=0;
    private EditText et_tuihuo_number;
    private EditText et_remarke,et_pici_no;
    private int storePosition,storePosition2=0;
    private WorkStateBean workStateBean;
    private BottomTongYongDialog dialogTHJXS;
    private BottomTongYongDialog dialogCPName;
    private WorkStateBean chanPinBean;
    private Spinner shape_sp_jxs;
    private ListDataSave<String> dataSave;
    private boolean isHeadBack=true;
    private long userId;
    private String username;
    private OrderEditHeadRequest orderEditHeadRequest;
    private OrderEditRequest orderEditRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editorder);
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        userId=MyApplication.mSettings.getLong("personid",0);
        username=MyApplication.mSettings.getString("username","");
        dataSave=new ListDataSave<>();
//        enterpriseId = prefs.getLong("enterpriseId", 0);
        initView();
        initSecendView();
        //MA.156.M0.100366.0c0116727025.S0238040.M230220.L20230211.V260219.C8
        if(usertype==UserType._GONG_CHANG.getTypeID()){
            //当userType等于1时，该用户为厂商
            initValue();
        }
        List<String> dataList = dataSave.getDataList(userId+MyApplication.NEW_EDIT_ORDER);
        codeStringList.clear();
        if(dataList!=null&&dataList.size()>0){
            codeStringList.addAll(dataList);
            scancount_tv.setText(codeStringList.size()+"");
        }
        if(Debug.isDebuggerConnected()){
            resultStringList = new ArrayList<>();
            resultStringList.add("MA.156.M0.100366.11412021.S0101.M230411.L20230401.V260410.C0");
            resultStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C1\nMA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C4");
            resultStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C2\n" +
                    "MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C9\n" +
                    "MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C9");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C4");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C5");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C6");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C7");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C8");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C9");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C10");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260702.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260703.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260704.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260705.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260708.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260707.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260709.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260701.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230711.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230712.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230713.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230715.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230716.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230717.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230718.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230719.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230710.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230700.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230701.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230702.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230703.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230704.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230705.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230706.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230708.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230709.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205781.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205780.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205783.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205784.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205785.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205786.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205787.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205788.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205789.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030010.S0205782.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030011.S0205782.M230707.L20230714.V260706.C3");
//            codeStringList.add("MA.156.M0.100366.0c01030012.S0205782.M230707.L20230714.V260706.C3");
            scancount_tv.setText(codeStringList.size()+"");

        }
        setDResultata();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(isHeadBack){
            //如果手动退出需要加一个缓存把退库信息缓存到本地
            dataSave.setDataList(userId+MyApplication.NEW_EDIT_ORDER,codeStringList);
        }else{
            dataSave.setDataList(userId+MyApplication.NEW_EDIT_ORDER,new ArrayList<String>());
        }
    }
    private void initSecendView() {
        //退货经销商
        et_di=(EditText)findViewById(R.id.et_di);
        et_guige=(EditText)findViewById(R.id.et_guige);
        et_tuihuo_number=(EditText)findViewById(R.id.et_tuihuo_number);
        et_remarke =(EditText)findViewById(R.id.et_remarke);
        et_pici_no=(EditText)findViewById(R.id.et_pici_no);
        LinearLayout ll_tuihuo_cangku = (LinearLayout) findViewById(R.id.ll_tuihuo_cangku);
//退货经销商的选择模块
        TextView spinner=(TextView)findViewById(R.id.shape_sp);
        shape_sp_jxs=(Spinner)findViewById(R.id.shape_sp_jxs);
        if(usertype==UserType._GONG_CHANG.getTypeID()){
            //当userType等于1时，该用户为厂商
            spinner.setVisibility(View.VISIBLE);
            shape_sp_jxs.setVisibility(View.GONE);
            ll_tuihuo_cangku.setVisibility(View.VISIBLE);
        }else{
            //当userType等于1时，该用户为厂商
            ll_tuihuo_cangku.setVisibility(View.GONE);
            spinner.setVisibility(View.GONE);
            shape_sp_jxs.setVisibility(View.VISIBLE);
            //
            //搜索退货经销商
            DealerRequest dealerRequest = new DealerRequest();
            GetJXSDealerListAsyn getDealerListAsyn = new GetJXSDealerListAsyn();
            getDealerListAsyn.execute(dealerRequest);

        }
        Button btn_head_submit = (Button) findViewById(R.id.btn_head_submit);
        btn_head_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(chanPinBean==null){
                    showToast("请选择产品!");
                    return;
                }
                if(usertype==UserType._GONG_CHANG.getTypeID()&&storePosition2==0){
                    //当userType等于1时，该用户为厂商并且仓库未选择
                    ToastUtils.show(NewEditOrderActivity.this,"请选择退货仓库");
                    return;
                }
//                if(usertype==UserType._JING_XIAO_SHANG.getTypeID()&&dealerPositon==0){//经销商，并且经销商的未选择
//                    showToast("请选择经销商!");
//                    return;
//                }
                if(usertype==UserType._GONG_CHANG.getTypeID()&&workStateBean==null){
                    //当userType等于1时，该用户为厂商并且仓库未选择
                    ToastUtils.show(NewEditOrderActivity.this,"请选择经销商!");
                    return;
                }
                if(et_tuihuo_number.getText().length()<=0){
                    showToast("请输入退货数量!");
                    return;
                }

                DialogUitl.showTishiSubmitDailog(NewEditOrderActivity.this,
                        new DialogUitl.DialogClickCallBack() {
                            @Override
                            public void okButtonClick() {
                                SubHeadHttp();
                            }

                            @Override
                            public void cancleButtonClick() {

                            }
                        });
            }
        });

        spinner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//展示选择的弹框
                searchJXS("");
                dialogTHJXS=new BottomTongYongDialog(dealerList,"选择退货经销商");
                dialogTHJXS.showDialog(NewEditOrderActivity.this);
                dialogTHJXS.setTextChangedLisner(new DialogTextCHangedLinstner() {
                    @Override
                    public void textChanged(String text) {
                        searchJXS(text);
                    }
                });
                dialogTHJXS.setOnclickLisner(new DialogCloseLinstner() {
                    @Override
                    public void closeLinstner(WorkStateBean bean) {
                        workStateBean=bean;
                        for (int i = 0; i < dealerList.size(); i++) {
                            if (dealerList.get(i).getId().equals(workStateBean.getId())){
                                dealerList.get(i).setSelect(true);
                            }else{
                                dealerList.get(i).setSelect(false);

                            }
                        }
                        spinner.setText(bean.getName());
                    }
                });
            }
        });
//        产品

//        产品的选择

        TextView sp_cp_name = (TextView) findViewById(R.id.sp_cp_name);
        sp_cp_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//展示选择的弹框

                //产品信息列表
                searchCP("");
                dialogCPName=new BottomTongYongDialog(chanPinList,"选择产品");
                dialogCPName.showDialog(NewEditOrderActivity.this);
                dialogCPName.setTextChangedLisner(new DialogTextCHangedLinstner() {
                    @Override
                    public void textChanged(String text) {
                        searchCP(text);
                    }
                });
                dialogCPName.setOnclickLisner(new DialogCloseLinstner() {
                    @Override
                    public void closeLinstner(WorkStateBean bean) {
                        chanPinBean=bean;
                        for (int i = 0; i < chanPinList.size(); i++) {
                            if (chanPinList.get(i).getId().equals(chanPinBean.getId())){
                                chanPinList.get(i).setSelect(true);
                            }else{
                                chanPinList.get(i).setSelect(false);

                            }
                        }
                        sp_cp_name.setText(bean.getName());
                        et_di.setText(bean.getDI());
                        et_guige.setText(bean.getStandard());
                    }
                });
            }
        });



        //退货经销商
        jxsAdapter = new ArrayAdapter<String>(NewEditOrderActivity.this, R.layout.simple_spinner_item1, dealerListName) {

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = View.inflate(getContext(), R.layout.new_activity_store_spinner_item, null);
                TextView label = (TextView) view.findViewById(R.id.store_spinner_item_ckmc_text);
                ImageView check = (ImageView) view.findViewById(R.id.store_spinner_item_ckmc_cb);
                label.setText(dealerListName.get(position));

                if (shape_sp_jxs.getSelectedItemPosition() == position) {
                    check.setImageResource(R.drawable.invent_select);
                    // viewHolder.selectBtn.setVisibility(View.GONE);
                } else {
                    check.setImageResource(R.drawable.invent_noselect);
                }
                return view;
            }
        };
        shape_sp_jxs.setAdapter(jxsAdapter);
        shape_sp_jxs.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                dealerPositon=position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });

//        sp_cp_name=(Spinner)findViewById(R.id.sp_cp_name);
//        cpAdapter = new ArrayAdapter<String>(NewEditOrderActivity.this, R.layout.simple_spinner_item1, ChanPinListName) {
//
//            @Override
//            public View getDropDownView(int position, View convertView, ViewGroup parent) {
//                View view = View.inflate(getContext(), R.layout.new_activity_store_spinner_item, null);
//                TextView label = (TextView) view.findViewById(R.id.store_spinner_item_ckmc_text);
//                ImageView check = (ImageView) view.findViewById(R.id.store_spinner_item_ckmc_cb);
//                label.setText(ChanPinListName.get(position));
//
//
//                if (sp_cp_name.getSelectedItemPosition() == position) {
//                    check.setImageResource(R.drawable.invent_select);
//                    // viewHolder.selectBtn.setVisibility(View.GONE);
//                } else {
//                    check.setImageResource(R.drawable.invent_noselect);
//                }
//                return view;
//            }
//        };
//        sp_cp_name.setAdapter(cpAdapter);
//        sp_cp_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                // TODO Auto-generated method stub
//                if(position!=0){
//                    et_di.setText(chanPinList.get(position).getDI());
//                    et_guige.setText(chanPinList.get(position).getStandard());
//
//                }
//                chanPinPosition=position;
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//                // TODO Auto-generated method stub
//
//            }
//        });
    }

    private void searchJXS(String text) {
        //搜索退货经销商
        DealerRequest dealerRequest = new DealerRequest();
        dealerRequest.setName(text);
        GetDealerListAsyn getDealerListAsyn = new GetDealerListAsyn();
        getDealerListAsyn.execute(dealerRequest);

    }

    private void SubHeadHttp() {

        progressDialog = ProgressDialog.show(this, getString(R.string.alert_title),
                "正在提交", true, false);
        orderEditHeadRequest=new OrderEditHeadRequest();
        orderEditHeadRequest.setChangeDesc(et_remarke.getText().toString()+"");
        orderEditHeadRequest.setMaterialId(chanPinBean.getId());
        if(usertype==UserType._GONG_CHANG.getTypeID()){
            if(workStateBean!=null)
                orderEditHeadRequest.setSupplierId(workStateBean.getId()+"");
            orderEditHeadRequest.setDepotId(storeList.get(storePosition2).getId());
        }else{
            if(dealerPositon!=0)
                orderEditHeadRequest.setSupplierId(dealerList.get(dealerPositon).getId());
        }

        orderEditHeadRequest.setBatchNumber(et_pici_no.getText().toString());
        orderEditHeadRequest.setCounts(et_tuihuo_number.getText().toString());

        orderEditHeadRequest.setUserId(userId+"");
        HeadBackReturnAsyn outStorageAsyn = new HeadBackReturnAsyn();
        outStorageAsyn.execute(orderEditHeadRequest);
    }

    private void initValue() {


        progressDialog = ProgressDialog.show(this, getString(R.string.alert_title), getString(R.string.alert_message),
                true, false);

        GetStoreRuest storeRequest = new GetStoreRuest();
        storeRequest.setUserId(userId);
        GetStorageListAsyn getStorageListAsyn = new GetStorageListAsyn();
        getStorageListAsyn.execute(storeRequest);
    }

    private void initView() {
        LinearLayout ll_head_back = (LinearLayout) findViewById(R.id.ll_head_back);
        LinearLayout ll_saoma_back=(LinearLayout)findViewById(R.id.ll_saoma_back);
        LinearLayout ll_head_content = (LinearLayout) findViewById(R.id.ll_head_content);
        LinearLayout ll_saoma_content=(LinearLayout)findViewById(R.id.ll_saoma_content);
        View iv_saoma_back=(View)findViewById(R.id.iv_saoma_back);
        View iv_head_back=(View)findViewById(R.id.iv_head_back);
        TextView tv_saoma_back=findViewById(R.id.tv_saoma_back);
        TextView tv_head_back=findViewById(R.id.tv_head_back);

        //默认
        tv_saoma_back.setTextColor(getResources().getColor(R.color.main_color));
        tv_head_back.setTextColor(getResources().getColor(R.color.font_black));
        iv_saoma_back.setVisibility(View.VISIBLE);
        iv_head_back.setVisibility(View.INVISIBLE);
        ll_saoma_content.setVisibility(View.VISIBLE);
        ll_head_content.setVisibility(View.GONE);


        ll_head_back.setOnClickListener(view -> {
            iv_saoma_back.setVisibility(View.INVISIBLE);
            iv_head_back.setVisibility(View.VISIBLE);
            ll_head_content.setVisibility(View.VISIBLE);
            ll_saoma_content.setVisibility(View.GONE);
            tv_saoma_back.setTextColor(getResources().getColor(R.color.font_black));
            tv_head_back.setTextColor(getResources().getColor(R.color.main_color));

        });
        ll_saoma_back.setOnClickListener(view -> {
            tv_saoma_back.setTextColor(getResources().getColor(R.color.main_color));
            tv_head_back.setTextColor(getResources().getColor(R.color.font_black));
            iv_saoma_back.setVisibility(View.VISIBLE);
            iv_head_back.setVisibility(View.INVISIBLE);
            ll_saoma_content.setVisibility(View.VISIBLE);
            ll_head_content.setVisibility(View.GONE);
            //测试扫码功能
//            startActivityForResult(new Intent(this, DefScanActivity.class),1000);
        });
        findViewById(R.id.all_top_back_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isHeadBack=true;
                finish();
            }
        });
        findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(codeStringList.size()<=0){
                    Toast.makeText(NewEditOrderActivity.this,"请先扫码",Toast.LENGTH_LONG).show();
                    return;
                }
                DialogUitl.showTongyongSubmitDailog(NewEditOrderActivity.this,
                        "提示","您确定清空"+codeStringList.size()+"条扫码记录嘛？",
                        new DialogUitl.DialogClickCallBack() {
                            @Override
                            public void okButtonClick() {
                                resultStringList.clear();
                                codeStringList.clear();
                                stringAdapater.notifyDataSetChanged();
                                scancount_tv.setText(codeStringList.size() + "");
                                dataSave.setDataList(userId+MyApplication.NEW_EDIT_ORDER,new ArrayList<String>());
                            }

                            @Override
                            public void cancleButtonClick() {

                            }
                        });

            }
        });
        TextView textView=(TextView)findViewById(R.id.all_top_title);
        textView.setText("退   货");
        editText=(EditText)findViewById(R.id.desc_edit);
        scancount_tv =(TextView)findViewById(R.id.scancount_tv);
        listView=(ListView)findViewById(R.id.edit_list);
        LinearLayout ll_changshang = (LinearLayout) findViewById(R.id.ll_changshang);
        usertype = MyApplication.mSettings.getInt("usertype", UserType._GONG_CHANG.getTypeID());
        if(usertype==UserType._GONG_CHANG.getTypeID()){
            //当userType等于1时，该用户为厂商
            ll_changshang.setVisibility(View.VISIBLE);
            initSpinnerView();
            initSpinnerView2();
        }else{
            //当userType不等于1时，该用户为经销商
            ll_changshang.setVisibility(View.GONE);
        }


        stringAdapater=new HwScanAdapter(this, codeStringList, new INewAdapterClick() {
            @Override
            public void onItemClick(View view, int position) {
                //点击删除回调接口
                deleteData(position);

            }
        });
        listView.setAdapter(stringAdapater);
        ((TextView)findViewById(R.id.out_storage_smrkxm_btn)).setText("扫码退货");
        ((TextView)findViewById(R.id.out_storage_smrkxm_btn_hw)).setText("红外扫码退货");
        ((TextView)findViewById(R.id.edit_qrck_btn)).setText("退  货");
        findViewById(R.id.out_storage_smrkxm_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intents.Scan.ACTION);
                intent.putExtra(Intents.Scan.IS_BULT_MODE, true);
                startActivityForResult(intent, 20);
            }
        });
        findViewById(R.id.out_storage_smrkxm_btn_hw).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewEditOrderActivity.this, HWDialogActivity.class);
                intent.putExtra("type", "lx");
                startActivityForResult(intent, 505);
            }
        });
        findViewById(R.id.edit_qrck_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(codeStringList.size()<1){
                    showToast("请扫码!");
                    return;
                }
                if(usertype==UserType._GONG_CHANG.getTypeID()&&storePosition==0){
                    //当userType等于1时，该用户为厂商
                    ToastUtils.show(NewEditOrderActivity.this,"请选择退货仓库");
                    return;
                }
                DialogUitl.showTishiDailog(NewEditOrderActivity.this,
                        codeStringList.size()+"",
                        new DialogUitl.DialogClickCallBack() {
                            @Override
                            public void okButtonClick() {
                                boolean b = NetWorkManger.hasNet(getApplicationContext());
                                if(b)
                                    subVerifyHttp();
                                else
                                    ToastUtils.show(getApplicationContext(),"暂无网络");
                            }

                            @Override
                            public void cancleButtonClick() {

                            }
                        });

            }
        });
    }

    private void searchCP(String s) {
        ChanPinRequest chanPinRequest = new ChanPinRequest();
        chanPinRequest.setName(s);
        GetChanPinListAsyn getChanPinListAsyn = new GetChanPinListAsyn();
        getChanPinListAsyn.execute(chanPinRequest);
    }

    //初始化退货仓库列表以及事件，如果是经销商则不需要
    private void initSpinnerView() {
        // 仓库
        ckSpinner = (Spinner) findViewById(R.id.in_storage_ckmc_spinner);
        ckAdapter = new ArrayAdapter<String>(this, R.layout.simple_spinner_item1, storeListName) {

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = View.inflate(getContext(), R.layout.new_activity_store_spinner_item, null);
                TextView label = (TextView) view.findViewById(R.id.store_spinner_item_ckmc_text);
                ImageView check = (ImageView) view.findViewById(R.id.store_spinner_item_ckmc_cb);
                label.setText(storeListName.get(position));

                if (ckSpinner.getSelectedItemPosition() == position) {
                    check.setImageResource(R.drawable.invent_select);
                    // viewHolder.selectBtn.setVisibility(View.GONE);
                } else {
                    check.setImageResource(R.drawable.invent_noselect);
                }
                return view;
            }
        };

//        adapter.setDropDownViewResource(R.layout.new_activity_store_spinner_item);
        ckSpinner.setAdapter(ckAdapter);
        ckSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                storePosition=position;
                myHandler.sendEmptyMessage(1);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }
    //初始化退货仓库列表以及事件，如果是经销商则不需要
    private void initSpinnerView2() {
        // 仓库
        ckSpinner2 = (Spinner) findViewById(R.id.in_storage_ckmc_spinner2);
        ckAdapter2 = new ArrayAdapter<String>(this, R.layout.simple_spinner_item1, storeListName) {

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = View.inflate(getContext(), R.layout.new_activity_store_spinner_item, null);
                TextView label = (TextView) view.findViewById(R.id.store_spinner_item_ckmc_text);
                ImageView check = (ImageView) view.findViewById(R.id.store_spinner_item_ckmc_cb);
                label.setText(storeListName.get(position));

                if (ckSpinner2.getSelectedItemPosition() == position) {
                    check.setImageResource(R.drawable.invent_select);
                    // viewHolder.selectBtn.setVisibility(View.GONE);
                } else {
                    check.setImageResource(R.drawable.invent_noselect);
                }
                return view;
            }
        };

//        adapter.setDropDownViewResource(R.layout.new_activity_store_spinner_item);
        ckSpinner2.setAdapter(ckAdapter2);
        ckSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                storePosition2=position;
                myHandler.sendEmptyMessage(6);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }

    private void deleteData(int position) {
        DialogUitl.showDeleteDailog(
                NewEditOrderActivity.this,
                codeStringList.get(position),
                (codeStringList.size() - position) + "", new DialogUitl.DialogClickCallBack() {
                    @Override
                    public void okButtonClick() {
                        codeStringList.remove(position);
                        scancount_tv.setText(codeStringList.size()+"");
                        stringAdapater.notifyDataSetChanged();
                    }

                    @Override
                    public void cancleButtonClick() {

                    }
                });
    }
    //校验提交
    private void subVerifyHttp() {


        progressDialog = ProgressDialog.show(this, getString(R.string.alert_title),
                "正在提交", true, false);
        orderEditRequest=new OrderEditRequest();
        orderEditRequest.setChangeDesc(editText.getText().toString()+"");
        orderEditRequest.setCodeList(codeStringList);
        if(usertype== UserType._GONG_CHANG.getTypeID()){
            orderEditRequest.setDepotId(storeList.get(storePosition).getId());
        }

        orderEditRequest.setUserID(userId);
//        subHttp();
//        progressDialog.dismiss();
//        isHeadBack=false;
//        NewEditOrderActivity.this.finish();
        BackReturnVerifyAsyn outStorageVerifyAsyn = new BackReturnVerifyAsyn();
        outStorageVerifyAsyn.execute(orderEditRequest);
//        Toast.makeText(getApplicationContext(),"请求开始",
//                Toast.LENGTH_LONG).show();
    }
    //后台提交到
    private void subHttp() {
        orderEditRequest=new OrderEditRequest();
        orderEditRequest.setChangeDesc(editText.getText().toString()+"");
        orderEditRequest.setUserID(userId);
        if(usertype==UserType._GONG_CHANG.getTypeID()){
            orderEditRequest.setCodeList(codeStringList);
            orderEditRequest.setDepotId(storeList.get(storePosition).getId());
            BackReturnAsyn outStorageAsyn = new BackReturnAsyn();
            outStorageAsyn.execute(orderEditRequest);
        }else{//经销商退货
            orderEditRequest.setCodeLst(codeStringList);
            BackReturnJXSAsyn outStorageAsyn = new BackReturnJXSAsyn();
            outStorageAsyn.execute(orderEditRequest);
        }


//        Http(request, getString(R.string.returnGoodsAPP), progressDialog, new RetrofitHttpListener() {
//            @Override
//            public void OnJson(String str) {
//                ResultInfo resultInfo= GsonUtil.GsonToBean(str,ResultInfo.class);
//                if (resultInfo!=null){
//                    showToast(resultInfo.getResultinfo());
//                    if (resultInfo.getResult()>0){
//                        finish();
//                    }
//                }
//            }
//        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1000){
            ToastUtils.show(this,"澈哥哥");
            return;
        }
        if(data!=null)
            resultStringList = data.getStringArrayListExtra(Intents.Scan.RESULTLIST);
        else
            resultStringList=new ArrayList<>();

        setDResultata();
    }
    private void setDResultata() {
        if (resultStringList==null){
            return;
        }

        for (int i=0;i<resultStringList.size();i++){
            if (resultStringList.get(i).contains("=")){
                String s=resultStringList.get(i);
                s=s.substring(s.indexOf("=")+1);
                resultStringList.set(i,s);
            }
            String result = resultStringList.get(i);
            result=result.replaceAll("\n","");
            String[] parts = result.split("MA.156.M0");
            if (parts.length >= 3) {//"包含2个\"MA.156.M0\""
                //
                for (int j = 0; j < parts.length; j++) {
                    if (j==1){
                        if (!resultStringList.contains("MA.156.M0"+parts[1])){
                            resultStringList.set(i,"MA.156.M0"+parts[1]);
                        }

                    }else if(j>1){
                        if (!resultStringList.contains("MA.156.M0"+parts[j])){
                            resultStringList.add(i+j+1-2,"MA.156.M0"+parts[j]);
                        }
                    }
                }
//                resultStringList.set(i,"MA.156.M0"+parts[1]);
//                resultStringList.add(i+1,"MA.156.M0"+parts[2]);
            }

        }
        if (resultStringList.size() == 0) {
            return;
        }
        codeStringList.addAll(0,GetOneList());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            codeStringList = codeStringList.stream().distinct().collect(Collectors.toList());
        }
        myHandler.sendEmptyMessage(2);
        stringAdapater.setList(codeStringList);
        stringAdapater.notifyDataSetChanged();
    }
    private List< String> GetOneList() {
        List<String> strings=new ArrayList<>();

        for (String str:resultStringList){
            if (!codeStringList.contains(str)){
                strings.add(str);
            }
        }
        if (strings.size()<1&&resultStringList.size()>0){
            showToast("该组码内容重复扫码");
        }else if (strings.size()!=resultStringList.size()){
            showToast("存在重复扫码，已自动过滤");
        }
        return strings;
    }
    /**
     * 获取经销商列表
     *
     * @author tjh
     *
     */
//    private class GetDealerListAsyn extends MyAsyncTask {
//
//        @Override
//        protected void onPostExecute(Object res) {
//            if (res == null || res.equals("")) {
//                Toast.makeText(NewEditOrderActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
//            } else {
//                com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
//                        .fromJSON((String) res, com.gogowan.agroenterprise.model.Message.class);
//                String string = Utils.getMessageContent(message);
//
//                if (string == null || string.equals("")) {
//                    Toast.makeText(NewEditOrderActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG)
//                            .show();
//                } else {
//                    DealerListResult dealerListResult = (DealerListResult) Utils.fromJSON(string,
//                            DealerListResult.class);
//                    if (dealerListResult.getResult() > 0) {
//                        if (dealerListResult.getDealer() != null) {
//                            dealerList.clear();
//                            dealerListName.clear();
//                            for (int i = 0; i < dealerListResult.getDealer().size(); i++) {
//                                dealerList.add(dealerListResult.getDealer().get(i));
//                                dealerListName.add(dealerListResult.getDealer().get(i).getDealerName());
//                            }
//                            myHandler.sendEmptyMessage(0);
//                        }
//                    } else {
//                        Toast.makeText(NewEditOrderActivity.this, dealerListResult.getResultinfo(), Toast.LENGTH_LONG)
//                                .show();
//                    }
//                }
//            }
//            progressDialog.dismiss();
//            super.onPostExecute(res);
//        }
//
//        @Override
//        protected Object doInBackground(Object... params) {
//            DealerRequest dealerRequest = (DealerRequest) params[0];
//            String json = Utils.toJSON(dealerRequest);
//            Log.i("gggggggggggggggggg===", json);
//            com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(14000, true,
//                    json);
//            // String ss = Utils.toJSON(message);
//            // Log.i("gggggggggggggggggg===", ss);
//            String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.returnGoodsAPP), message);
//            return res;
//        }
//    }
    /**
     * 厂商退货
     *
     * @author tjh
     *
     */
    private class BackReturnAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
            super.onPostExecute(res);
            //获取提交请求
            String str=Utils.toJSON(orderEditRequest);
            JSONObject data1 =null;
            if (res == null || res.equals("")) {
                Toast.makeText(NewEditOrderActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
                data1 = Utils.getDiffData(0,"扫码退货提交", "与服务器通讯失败", username, str);
            } else {
                try {
                    JSONObject jo=new JSONObject(res.toString());
                    Toast.makeText(getApplicationContext(),jo.getString("msg"),
                            Toast.LENGTH_LONG).show();
                    data1 = Utils.getDiffData(jo.getInt("code"),"扫码退货提交", jo.getString("msg"), username, str);
                }catch (Exception e){
                    Toast.makeText(getApplicationContext(),"返回值："+res,
                            Toast.LENGTH_LONG).show();
                    data1 = Utils.getDiffData(0, "扫码退货提交","数据解析失败！", username, str);
                    e.printStackTrace();
                }
            }
            String jaString = MyApplication.mSettings.getString(MyApplication.ALL_LOGS, "");
            try {
                JSONArray ja=null;
                if(StringUtils.isEmpty(jaString)){
                    ja=new JSONArray();
                }else{
                    ja=new JSONArray(jaString);

                }
                data1.put("usertype",usertype);
                ja.put(data1);
                MyApplication.editor.putString(MyApplication.ALL_LOGS,ja.toString());
                MyApplication.editor.commit();

            } catch (JSONException e) {
                e.printStackTrace();
            }
            super.onPostExecute(res);
            Log.d("NewEditOrderActivity",String.valueOf(res));
        }

        @Override
        protected Object doInBackground(Object... params) {
            OrderEditRequest outStorageRequest = (OrderEditRequest) params[0];

            String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.returnGoodsAPP),
                    outStorageRequest);
//            String res = Utils.getCommit(getString(R.string.first_url) + getString(R.string.addStorageReturnRecordApp)+
//                    "?codes="+outStorageRequest.getCodes()+"&personid="+outStorageRequest.getPersonid());
            return res;
        }
    }
    /**
     * 经销商退货
     *
     * @author tjh
     *
     */
    private class BackReturnJXSAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
            //获取提交请求
            String str=Utils.toJSON(orderEditRequest);
            JSONObject data1 =null;
            if (res == null || res.equals("")) {
                Toast.makeText(NewEditOrderActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
                data1 = Utils.getDiffData(0,"扫码退货提交", "与服务器通讯失败", username, str);
            } else {
                try {
                    JSONObject jo=new JSONObject(res.toString());
                    Toast.makeText(getApplicationContext(),jo.getString("msg"),
                            Toast.LENGTH_LONG).show();
                    data1 = Utils.getDiffData(jo.getInt("code"),"扫码退货提交", jo.getString("msg"), username, str);
                }catch (Exception e){
                    Toast.makeText(getApplicationContext(),"返回值："+res,
                            Toast.LENGTH_LONG).show();
                    data1 = Utils.getDiffData(0, "扫码退货提交","数据解析失败！", username, str);
                    e.printStackTrace();
                }
            }
            String jaString = MyApplication.mSettings.getString(MyApplication.ALL_LOGS, "");
            try {
                JSONArray ja=null;
                if(StringUtils.isEmpty(jaString)){
                    ja=new JSONArray();
                }else{
                    ja=new JSONArray(jaString);

                }
                data1.put("usertype",usertype);
                ja.put(data1);
                MyApplication.editor.putString(MyApplication.ALL_LOGS,ja.toString());
                MyApplication.editor.commit();

            } catch (JSONException e) {
                e.printStackTrace();
            }
            super.onPostExecute(res);
            Log.d("NewEditOrderActivity",String.valueOf(res));
        }

        @Override
        protected Object doInBackground(Object... params) {
            OrderEditRequest outStorageRequest = (OrderEditRequest) params[0];

            String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.returnGoodsSupplier),
                    outStorageRequest);
//            String res = Utils.getCommit(getString(R.string.first_url) + getString(R.string.addStorageReturnRecordApp)+
//                    "?codes="+outStorageRequest.getCodes()+"&personid="+outStorageRequest.getPersonid());
            return res;
        }
    }
    /**
     * 获取经销商的经销商列表
     *
     * @author tjh
     *
     */
    private class GetJXSDealerListAsyn extends MyAsyncTask {
        @Override
        protected void onPostExecute(Object res) {
            if (res == null || res.equals("")) {
                Toast.makeText(NewEditOrderActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
            } else {
                try {
                    JSONObject jo = new JSONObject(res.toString());
                    if (jo.getInt("code") != 200) {
                        Toast.makeText(getApplicationContext(), jo.getString("msg"), Toast.LENGTH_LONG).show();
                        return;
                    }
                    res = jo.getJSONArray("data").toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (res == null || res.equals("")) {
                    Toast.makeText(NewEditOrderActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG)
                            .show();
                } else {
                    Type userListType = new TypeToken<List<WorkStateBean>>() {
                    }.getType();
                    List<WorkStateBean> storeListResult = (List<WorkStateBean>) JsonUtils.fromJSON(res.toString(), userListType);
                    if (storeListResult!=null&&storeListResult.size() > 0) {
                        dealerList.clear();
                        dealerListName.add("请选择");
                        dealerList.add(new WorkStateBean());
                        dealerList.addAll(storeListResult);
                        for (int i = 0; i < storeListResult.size(); i++) {
                            dealerListName.add(storeListResult.get(i).getSupplier());
                        }

                        myHandler.sendEmptyMessage(10);
                    } else {
                        dealerList.clear();
                        myHandler.sendEmptyMessage(10);
                    }
                }
            }
//            progressDialog.dismiss();
            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            String userID="";
            if(usertype==UserType._GONG_CHANG.getTypeID()){
                String token = MyApplication.mSettings.getString("token", "");
                if(!StringUtils.isEmpty(token)&&token.split("_").length>=2){
                    userID=token.split("_")[1];
                }

            }else{
                userID=MyApplication.mSettings.getLong("personid",0)+"";
            }
            String res = Utils.getCommit(getString(R.string.first_url) +
                    getString(R.string.getSupplierList)+
                    "?personid="+userID);
            return res;
        }
    }
    /**
     * 退货校验
     *
     * @author tjh
     *
     */
    private class BackReturnVerifyAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
            progressDialog.dismiss();
            //获取提交请求
            String str=Utils.toJSON(orderEditRequest);
            JSONObject data1 =null;
            if (res == null || res.equals("")) {
                Toast.makeText(NewEditOrderActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
                data1 = Utils.getDiffData(0,"扫码退货校验", "与服务器通讯失败", username, str);
            } else {
                try {
                    JSONObject jo=new JSONObject(res.toString());
                    Toast.makeText(getApplicationContext(),jo.getString("msg"),
                            Toast.LENGTH_LONG).show();
                    data1 = Utils.getDiffData(jo.getInt("code"),"扫码退货校验", jo.getString("msg"), username, str);
                    if(jo.getInt("code")==200){
                        isHeadBack=false;
                        NewEditOrderActivity.this.finish();
                        subHttp();
                    }

                }catch (Exception e){
                    Toast.makeText(getApplicationContext(),"返回值："+res,
                            Toast.LENGTH_LONG).show();
                    data1 = Utils.getDiffData(0, "扫码退货校验","数据解析失败！", username, str);
                    e.printStackTrace();
                }
            }
            String jaString = MyApplication.mSettings.getString(MyApplication.ALL_LOGS, "");
            try {
                JSONArray ja=null;
                if(StringUtils.isEmpty(jaString)){
                    ja=new JSONArray();
                }else{
                    ja=new JSONArray(jaString);

                }
                assert data1 != null;
                data1.put("usertype",usertype);

                ja.put(data1);
                MyApplication.editor.putString(MyApplication.ALL_LOGS,ja.toString());
                MyApplication.editor.commit();

            } catch (JSONException e) {
                e.printStackTrace();
            }
            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            OrderEditRequest outStorageRequest = (OrderEditRequest) params[0];

            String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.returnGoodsVerify),
                    outStorageRequest);
//            String res = Utils.getCommit(getString(R.string.first_url) + getString(R.string.addStorageReturnRecordApp)+
//                    "?codes="+outStorageRequest.getCodes()+"&personid="+outStorageRequest.getPersonid());
            return res;
        }
    }
    /**
     * 手动退货
     *
     * @author tjh
     *
     */
    private class HeadBackReturnAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
            progressDialog.dismiss();
            //获取提交请求
            String str=Utils.toJSON(orderEditHeadRequest);
            JSONObject data1 =null;
            if (res == null || res.equals("")) {
                Toast.makeText(NewEditOrderActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
                data1 = Utils.getDiffData(0,"手动退货", "与服务器通讯失败", username, str);
            } else {
                try {
                    JSONObject jo=new JSONObject(res.toString());
                    Toast.makeText(getApplicationContext(),jo.getString("msg"),
                            Toast.LENGTH_LONG).show();
                    data1 = Utils.getDiffData(jo.getInt("code"),"手动退货", jo.getString("msg"), username, str);
                    if(jo.getInt("code")!=200){
                        return;
                    }
                    isHeadBack=false;
                    NewEditOrderActivity.this.finish();
                }catch (Exception e){
                    data1 = Utils.getDiffData(0, "手动退货","数据解析失败！", username, str);
                    e.printStackTrace();
                }
            }
            String jaString = MyApplication.mSettings.getString(MyApplication.ALL_LOGS, "");
            try {
                JSONArray ja=null;
                if(StringUtils.isEmpty(jaString)){
                    ja=new JSONArray();
                }else{
                    ja=new JSONArray(jaString);

                }
                data1.put("usertype",usertype);

                ja.put(data1);
                MyApplication.editor.putString(MyApplication.ALL_LOGS,ja.toString());
                MyApplication.editor.commit();

            } catch (JSONException e) {
                e.printStackTrace();
            }

            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            OrderEditHeadRequest outStorageRequest = (OrderEditHeadRequest) params[0];

            String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.returnSubmit),
                    outStorageRequest);
            return res;
        }
    }
    /**
     * 获取仓库列表
     *
     * @author tjh
     *
     */
    private class GetStorageListAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
            progressDialog.dismiss();
            if (res == null || res.equals("")) {
                Toast.makeText(NewEditOrderActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
            } else {
                try {
                    JSONObject jo=new JSONObject(res.toString());
                    if(jo.getInt("code")!=200){
                        Toast.makeText(getApplicationContext(),jo.getString("msg"),
                                Toast.LENGTH_LONG).show();
                        return;
                    }
                    Type userListType = new TypeToken<List<StoreModel>>() {
                    }.getType();
                    String str=jo.getJSONObject("data").getJSONArray("rows").toString();
                    List<StoreModel> storeListResult = (List<StoreModel>) JsonUtils.fromJSON(str, userListType);
                    if (storeListResult!= null) {
                        storeList.clear();
                        storeListName.clear();
                        storeListName.add("请选择");
                        storeList.add(new StoreModel());
//                        hwList.clear();
                        for (int i = 0; i < storeListResult.size(); i++) {
                            storeList.add(storeListResult.get(i));
//                            if ("不合格仓库".equals(storeListResult.get(i).getName())){
//                                dealerID=storeListResult.get(i).getId();
//                            }
                            storeListName.add(storeListResult.get(i).getName());
                        }

                    }
                    myHandler.sendEmptyMessage(1);
                    myHandler.sendEmptyMessage(6);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            GetStoreRuest storeRequest = (GetStoreRuest) params[0];
            return Utils.postCommit(getString(R.string.first_url) + getString(R.string.getAllListApp), storeRequest);
        }
    }
    /**
     * 获取经销商列表
     *
     * @author tjh
     */
    private class GetDealerListAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
            if (res == null || res.equals("")) {
                Toast.makeText(NewEditOrderActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
            } else {
                try {
                    JSONObject jo = new JSONObject(res.toString());
                    if (jo.getInt("code") != 200) {
                        Toast.makeText(getApplicationContext(), jo.getString("msg"), Toast.LENGTH_LONG).show();
                        return;
                    }
                    res = jo.getJSONObject("data").getJSONArray("rows").toString();
                } catch (Exception e) {

                }
                if (res == null || res.equals("")) {
                    Toast.makeText(NewEditOrderActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG)
                            .show();
                } else {
                    Type userListType = new TypeToken<List<WorkStateBean>>() {
                    }.getType();
                    List<WorkStateBean> storeListResult = (List<WorkStateBean>) JsonUtils.fromJSON(res.toString(), userListType);
                    if (storeListResult!=null&&storeListResult.size() > 0) {
                        dealerList.clear();
//                        dealerListName.add("请选择");
//                        dealerList.add(new WorkStateBean());
                        dealerList.addAll(storeListResult);
                        myHandler.sendEmptyMessage(0);
                    } else {
                        dealerList.clear();
                        myHandler.sendEmptyMessage(0);
                    }
                }
            }
//            progressDialog.dismiss();
            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            DealerRequest chanPinRequests= (DealerRequest) params[0];
            String res = Utils.postCommit(getString(R.string.first_url)
                    + getString(R.string.getSupplierListApp) ,chanPinRequests);
            return res;
        }
    }
    /**
     * 获取产品列表
     *
     * @author tjh
     */
    private class GetChanPinListAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
            if (res == null || res.equals("")) {
                Toast.makeText(NewEditOrderActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
            } else {
                try {
                    JSONObject jo = new JSONObject(res.toString());
                    if (jo.getInt("code") != 200) {
                        Toast.makeText(getApplicationContext(), jo.getString("msg"), Toast.LENGTH_LONG).show();
                        return;
                    }
                    res = jo.getJSONObject("data").getJSONArray("rows").toString();
                } catch (Exception e) {

                }
                if (res == null || res.equals("")) {
                    Toast.makeText(NewEditOrderActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG)
                            .show();
                } else {
                    Type userListType = new TypeToken<List<WorkStateBean>>() {
                    }.getType();
                    List<WorkStateBean> storeListResult = (List<WorkStateBean>) JsonUtils.fromJSON(res.toString(), userListType);
                    if (storeListResult!=null&&storeListResult.size() > 0) {
                        chanPinList.clear();
                        chanPinList.addAll(storeListResult);
                        myHandler.sendEmptyMessage(5);
                    } else {
                        chanPinList.clear();
                        myHandler.sendEmptyMessage(5);
                    }
                }
            }
//            progressDialog.dismiss();
            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            ChanPinRequest chanPinRequests= (ChanPinRequest) params[0];
            String res = Utils.postCommit(getString(R.string.first_url)
                    + getString(R.string.getMaterialListApp),chanPinRequests);
            return res;
        }
    }
}
